//
//  ReactiveDataRequest.swift
//  API
//
//  Created by ET|冰琳 on 2017/3/24.
//  Copyright © 2017年 IB. All rights reserved.
//

import Foundation
import ReactiveSwift
import Alamofire

// MARK: - ReactiveExtensionsProvider
extension DataRequest: ReactiveExtensionsProvider{}
extension Reactive where Base: DataRequest{
    
    /// response JSON
    func responseJSON<T: Error>(
        queue: DispatchQueue? = nil,
        options: JSONSerialization.ReadingOptions = .allowFragments)
        -> SignalProducer<Any, T>
    {
        return SignalProducer {[base = self.base] (observer, dispose) in
            
            let request = base.responseJSON(queue: queue, options: options, completionHandler: { (response) in
                
                switch response.result{
                case .failure(let err):
                    
                    #if DEBUG
                        print("[Error] [URL: \(response.request)] \n ~~~~ \(err)")
                        if let data = response.data, let str = String(data: data, encoding: .utf8) {
                            print("Error msg:",str)
                        }
                    #endif
                    observer.send(error: err as! T)
                case .success(let value):
                    
                    #if DEBUG
                        print("[SUCEED] [URL: \(response.request)] \n ~~~~ \(value)")
                    #endif
                    
                    observer.send(value: value)
                    observer.sendCompleted()
                }
            })
            
            dispose += {
                request.cancel()
            }
        }
    }
}
